# -*- encoding: utf8 -*-

import csv
from datetime import datetime
from StringIO import StringIO

from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
import settings

from reps.lib.pyExcelerator import Workbook
from reps.lib.PyRTF import Renderer, Elements

from reps.interns.forms import *
from reps.interns.models import *
from reps.interns.common import *
from reps.interns.helpers import teacher_only, teacher_or_dean_only, render
from reps.interns.genDOCX_2 import * #tu sa cztery metody i wszystkie wykorzystujemy :)


##########################################
# Teacher's and Dean's Reports Interface #
##########################################

@login_required
@teacher_or_dean_only
def reports(request):
    return render('reports.html', request)


def all_specs(teacher, dean):
    if teacher:
        return teacher.specialization_set.all()
    else:
        return dean.faculty.specialization_set.all()


@login_required
@teacher_or_dean_only
def show_hostel_report(request, teacher=None, dean=None):
    if  request.method=="POST":
        wb = Workbook()
        ws0 = wb.add_sheet('Akademik')
        
        startdate=request.POST['startdate']
        enddate=request.POST['enddate']
        first=Training_Date.objects.get(id=startdate).start_date
        last=Training_Date.objects.get(id=enddate).end_date
        dates = Training_Date.objects.filter(start_date__gte=first, end_date__lte=last)
        
        trainings = Training.objects.filter(hostel=True, is_archival=False, training_date__in=dates, socrates=False)#.order_by('last_name', 'first_name')
    
        specialization = Specialization.objects.get(id=request.POST['specialization'])
        students=Student.objects.filter(specialization=specialization)
        
        trainings.filter(student__in=students)
            
        ws0.write(0,0, "Zapotrzebowanie na miejsce w akademiku")
        ws0.write(1,0, "Grupa:")
        ws0.write(1,1, specialization.full_name)

        ws0.write(2,0, "Nr albumu")
        ws0.write(2,1, "Nazwisko")
        ws0.write(2,2, "Imię".decode("utf-8"))
        ws0.write(2,3, "Termin praktyki")
        
        i=3
        for training in trainings:
            ws0.write(i, 0, training.student.book_no)
            ws0.write(i, 1, training.student.profile.user.last_name)
            ws0.write(i, 2, training.student.profile.user.first_name)
            ws0.write(i, 3, "%s-%s" % (str(training.training_date.start_date), str(training.training_date.end_date)))
            i+=1
            
    
        wb.save(settings.DATA_CATALOG + 'akademik.xls')
        
        
        file=open(settings.DATA_CATALOG + 'akademik.xls', 'r')
        response = HttpResponse(file.read(), mimetype='application/ms-excel')
        response['Content-Disposition'] = 'attachment; filename=akademik.xls'
        file.close()
        return response
    else:
        title = 'Zakwaterowanie'
        initial = {}
        if 'selected_specialization' in request.session:
            initial['specialization'] = request.session['selected_specialization'].id
        specialization_choices = tuple((i.id, i.full_name)
                                       for i in all_specs(teacher, dean))
        start_choices=()
        end_choices=()
        tmp=None
        tmp1=None
        msg=None
        
        for training_date in Training_Date.objects.all():
            if len(training_date.training_set.filter(is_archival=False))==0:
                continue
            if tmp is None:
                tmp=training_date.start_date
                tmp1=training_date.start_date
                initial['startdate']=training_date.id

            if training_date.start_date.year==datetime.today().year and training_date.start_date<tmp:
                initial['startdate']=training_date.id
                tmp=training_date.start_date

            if training_date.end_date>tmp1:
                initial['enddate']=training_date.id
                tmp1=training_date.end_date
            
            start_choices += tuple([(training_date.id,training_date.start_date)])
            end_choices += tuple([(training_date.id,training_date.end_date)])
        
        if len(end_choices)==0:
            msg='Brak aktywnych praktyk'
        
        form = ReportForm(initial=initial,
                                      specchoices=specialization_choices, startchoices=start_choices, endchoices=end_choices)
        return render('reports.html', request, {'title':title, 'form': form, 'msg': msg})

@login_required
@teacher_or_dean_only
def show_fail_report(request, teacher=None, dean=None):
    if request.method=="POST":
        wb = Workbook()
        ws0 = wb.add_sheet('Akademik')
        
        startdate=request.POST['startdate']
        enddate=request.POST['enddate']
        first=Training_Date.objects.get(id=startdate).start_date
        last=Training_Date.objects.get(id=enddate).end_date
        dates = Training_Date.objects.filter(start_date__gte=first, end_date__lte=last)
        
        trainings = Training.objects.filter(is_archival=True, pass_date=None, training_date__in=dates)#.order_by('last_name', 'first_name')
        
        specialization = Specialization.objects.get(id=request.POST['specialization'])
        students=Student.objects.filter(specialization=specialization)
        
        trainings.filter(student__in=students)

        ws0.write(0,0, "Niezaliczone praktyki")
        ws0.write(1,0, "Grupa:")
        ws0.write(1,1, specialization.full_name)
        i=2
            
        ws0.write(i,0, "Lp.")
        ws0.write(i,1, "Nr albumu")
        ws0.write(i,2, "Nazwisko i Imię".decode("utf-8"))
        ws0.write(i,3, "Miejscowość".decode("utf-8"))
        ws0.write(i,4, "Nazwa firmy")
        ws0.write(i,5, "Miejsce odbywania praktyki")
        ws0.write(i,6, "Termin praktyki")
        ws0.write(i,7, "Płatna?".decode("utf-8"))
        ws0.write(i,8, "Zagraniczna?")
        i+=1
    
        for training in trainings:
            ws0.write(i, 0, unicode(i-2))
            ws0.write(i, 1, training.student.book_no)
            ws0.write(i, 2, "%s %s" % (training.student.profile.user.last_name, training.student.profile.user.first_name))
            ws0.write(i, 3, "%s %s" % (training.postal_code, training.city))
            ws0.write(i, 4, training.branch.name)
            ws0.write(i, 5, "%s, %s %s" % (training.branch.street, training.branch.postal_code, training.branch.city))
            ws0.write(i, 6, "%s-%s" % (str(training.training_date.start_date), str(training.training_date.end_date)))
            if training.payable:
                ws0.write(i, 7, "Tak")
            else:
                ws0.write(i, 7, "Nie")
            if training.abroad():
                ws0.write(i, 8, "Tak")
            else:
                ws0.write(i, 8, "Nie")
            i+=1
            
    
        wb.save(settings.DATA_CATALOG + 'niezaliczone.xls')
        file=open(settings.DATA_CATALOG + 'niezaliczone.xls', 'r')
        response = HttpResponse(file.read(), mimetype='application/ms-excel')
        response['Content-Disposition'] = 'attachment; filename=niezaliczone.xls'
        file.close()
        
        return response
    else:
        title = 'Niezaliczone praktyki'
        initial = {}
        if 'selected_specialization' in request.session:
            initial['specialization'] = request.session['selected_specialization'].id
        specialization_choices = tuple((i.id, i.full_name)
                                       for i in all_specs(teacher, dean))
        start_choices=()
        end_choices=()
        tmp=None
        tmp1=None
        msg=None
        
        for training_date in Training_Date.objects.all():
            if len(training_date.training_set.filter(is_archival=True, pass_date=None))==0:
                continue
            if tmp is None:
                tmp=training_date.start_date
                tmp1=training_date.start_date
                initial['startdate']=training_date.id

            if training_date.start_date.year==datetime.today().year and training_date.start_date<tmp:
                initial['startdate']=training_date.id
                tmp=training_date.start_date

            if training_date.end_date>tmp1:
                initial['enddate']=training_date.id
                tmp1=training_date.end_date
            
            start_choices += tuple([(training_date.id,training_date.start_date)])
            end_choices += tuple([(training_date.id,training_date.end_date)])
        
        if len(end_choices)==0:
            msg='Brak niezaliczonych praktyk'
        
        form = ReportForm(initial=initial,
                                      specchoices=specialization_choices, startchoices=start_choices, endchoices=end_choices)
        return render('reports.html', request, {'title':title, 'form': form, 'msg': msg})


@login_required
@teacher_or_dean_only
def show_pass_report(request, teacher=None, dean=None):
    if request.method=="POST":
        wb = Workbook()
        ws0 = wb.add_sheet('Akademik')
        
        startdate=request.POST['startdate']
        enddate=request.POST['enddate']
        first=Training_Date.objects.get(id=startdate).start_date
        last=Training_Date.objects.get(id=enddate).end_date
        dates = Training_Date.objects.filter(start_date__gte=first, end_date__lte=last)
        
        trainings = Training.objects.filter(is_archival=True, training_date__in=dates).exclude(pass_date=None)
        
        specialization = Specialization.objects.get(id=request.POST['specialization'])
        students=Student.objects.filter(specialization=specialization)
        
        trainings.filter(student__in=students)

        ws0.write(0,0, "Zaliczone praktyki")
        ws0.write(1,0, "Grupa:")
        ws0.write(1,1, specialization.full_name)
        i=2
            
            
        ws0.write(i,0, "Lp.")
        ws0.write(i,1, "Nr albumu")
        ws0.write(i,2, "Nazwisko i Imię".decode("utf-8"))
        ws0.write(i,3, "Miejscowość".decode("utf-8"))
        ws0.write(i,4, "Nazwa firmy")
        ws0.write(i,5, "Miejsce odbywania praktyki")
        ws0.write(i,6, "Termin praktyki")
        ws0.write(i,7, "Płatna?".decode("utf-8"))
        ws0.write(i,8, "Zagraniczna?")
        i+=1
    
        for training in trainings:
            print training
            ws0.write(i, 0, unicode(i-2))
            ws0.write(i, 1, training.student.book_no)
            ws0.write(i, 2, "%s %s" % (training.student.profile.user.last_name, training.student.profile.user.first_name))
            ws0.write(i, 3, "%s %s" % (training.postal_code, training.city))
            ws0.write(i, 4, training.branch.name)
            ws0.write(i, 5, "%s, %s %s" % (training.branch.street, training.branch.postal_code, training.branch.city))
            ws0.write(i, 6, "%s-%s" % (str(training.training_date.start_date), str(training.training_date.end_date)))
            if training.payable:
                ws0.write(i, 7, "Tak")
            else:
                ws0.write(i, 7, "Nie")
            if training.abroad():
                ws0.write(i, 8, "Tak")
            else:
                ws0.write(i, 8, "Nie")
            i+=1
            
        wb.save(settings.DATA_CATALOG + 'zaliczone.xls')
        file=open(settings.DATA_CATALOG + 'zaliczone.xls', 'r')
        response = HttpResponse(file.read(), mimetype='application/ms-excel')
        response['Content-Disposition'] = 'attachment; filename=zaliczone.xls'
        file.close()
        
        return response
    else:
        title = 'Zaliczone praktyki'
        initial = {}
        if 'selected_specialization' in request.session:
            initial['specialization'] = request.session['selected_specialization'].id
        specialization_choices = tuple((i.id, i.full_name)
                                       for i in all_specs(teacher, dean))
        start_choices=()
        end_choices=()
        tmp=None
        tmp1=None
        msg=None
        
        for training_date in Training_Date.objects.all():
            if len(training_date.training_set.filter(is_archival=True).exclude(pass_date=None))==0:
                continue
            if tmp is None:
                tmp=training_date.start_date
                tmp1=training_date.start_date
                initial['startdate']=training_date.id

            if training_date.start_date.year==datetime.today().year and training_date.start_date<tmp:
                initial['startdate']=training_date.id
                tmp=training_date.start_date

            if training_date.end_date>tmp1:
                initial['enddate']=training_date.id
                tmp1=training_date.end_date
            
            start_choices += tuple([(training_date.id,training_date.start_date)])
            end_choices += tuple([(training_date.id,training_date.end_date)])
        
        if len(end_choices)==0:
            msg='Brak zaliczonych praktyk'
        
        form = ReportForm(initial=initial,
                                      specchoices=specialization_choices, startchoices=start_choices, endchoices=end_choices)
        return render('reports.html', request, {'title':title, 'form': form, 'msg': msg})


@login_required
@teacher_or_dean_only
def show_refund_report(request, teacher=None, dean=None):
    if request.method=="POST":
        wb = Workbook()
        ws0 = wb.add_sheet('Akademik')
        
        trainings = Training.objects.filter(is_archival=True)
        trainings = trainings.exclude(pass_date=None)
        trainings = trainings.filter(payable=False)

        startdate=request.POST['startdate']
        enddate=request.POST['enddate']
        first=Training_Date.objects.get(id=startdate).start_date
        last=Training_Date.objects.get(id=enddate).end_date
        dates = Training_Date.objects.filter(start_date__gte=first, end_date__lte=last)
        
        trainings = trainings.filter(training_date__in=dates)#.order_by('last_name', 'first_name')

        specialization = Specialization.objects.get(id=request.POST['specialization'])
        students=Student.objects.filter(specialization=specialization)
        
        trainings.filter(student__in=students)

	trainings = [x for x in trainings if x.branch.city != x.city]

        ws0.write(0,0, "Lista do kwestury")
        ws0.write(1,0, "Grupa:")
        ws0.write(1,1, specialization.full_name)
        i=2
            
            
        ws0.write(i,0, "Lp.")
        ws0.write(i,1, "Nr albumu")
        ws0.write(i,2, "Nazwisko i Imię".decode("utf-8"))
        ws0.write(i,3, "Miejscowość".decode("utf-8"))
        ws0.write(i,4, "Nazwa firmy")
        ws0.write(i,5, "Miejsce odbywania praktyki")
        ws0.write(i,6, "Termin praktyki")
        ws0.write(i,7, "Płatna?".decode("utf-8"))
        ws0.write(i,8, "Zagraniczna?")
        i+=1
    
        for training in trainings:
            ws0.write(i, 0, unicode(i-2))
            ws0.write(i, 1, training.student.book_no)
            ws0.write(i, 2, "%s %s" % (training.student.profile.user.last_name, training.student.profile.user.first_name))
            ws0.write(i, 3, "%s %s" % (training.postal_code, training.city))
            ws0.write(i, 4, training.branch.name)
            ws0.write(i, 5, "%s, %s %s" % (training.branch.street, training.branch.postal_code, training.branch.city))
            ws0.write(i, 6, "%s-%s" % (str(training.training_date.start_date), str(training.training_date.end_date)))
            if training.payable:
                ws0.write(i, 7, "Tak")
            else:
                ws0.write(i, 7, "Nie")
            if training.abroad():
                ws0.write(i, 8, "Tak")
            else:
                ws0.write(i, 8, "Nie")
            i+=1
            
        
        wb.save(settings.DATA_CATALOG + 'kwestura.xls')
        file=open(settings.DATA_CATALOG + 'kwestura.xls', 'r')
        response = HttpResponse(file.read(), mimetype='application/ms-excel')
        response['Content-Disposition'] = 'attachment; filename=kwestura.xls'
        file.close()
        return response
    else:
        title = 'Lista do kwestury'
        initial = {}
        if 'selected_specialization' in request.session:
            initial['specialization'] = request.session['selected_specialization'].id
        specialization_choices = tuple((i.id, i.full_name)
                                       for i in all_specs(teacher, dean))
        start_choices=()
        end_choices=()
        tmp=None
        tmp1=None
        msg=None
        
        for training_date in Training_Date.objects.all():
            if len(training_date.training_set.filter(is_archival=True, payable=False).exclude(pass_date=None))==0:
                continue
            if tmp is None:
                tmp=training_date.start_date
                tmp1=training_date.start_date
                initial['startdate']=training_date.id

            if training_date.start_date.year==datetime.today().year and training_date.start_date<tmp:
                initial['startdate']=training_date.id
                tmp=training_date.start_date

            if training_date.end_date>tmp1:
                initial['enddate']=training_date.id
                tmp1=training_date.end_date
            
            start_choices += tuple([(training_date.id,training_date.start_date)])
            end_choices += tuple([(training_date.id,training_date.end_date)])
        
        if len(end_choices)==0:
            msg='Brak praktyk na listę do kwestury'
        
        form = ReportForm(initial=initial,
                                      specchoices=specialization_choices, startchoices=start_choices, endchoices=end_choices)
        return render('reports.html', request, {'title':title, 'form': form, 'msg': msg})



@login_required
@teacher_or_dean_only
def generate_contracts(request, teacher=None, dean=None):
    if request.method=="POST":
        trainings = Training.objects.filter(is_archival=False, locked=True, dont_print_contract=False)
        
        startdate=request.POST['startdate']
        enddate=request.POST['enddate']
        first=Training_Date.objects.get(id=startdate).start_date
        last=Training_Date.objects.get(id=enddate).end_date
        dates = Training_Date.objects.filter(start_date__gte=first, end_date__lte=last)
        
        trainings = trainings.filter(training_date__in=dates)

        specialization = Specialization.objects.get(id=request.POST['specialization'])
        students=Student.objects.filter(specialization=specialization)
        
        trainings.filter(student__in=students)

        createDOCX(settings.DATA_CATALOG + 'umowy.docx', generateAgreement, trainings)
        file=open(settings.DATA_CATALOG + 'umowy.docx', 'r')
        response = HttpResponse(file.read(), mimetype='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
        response['Content-Disposition'] = 'attachment; filename=umowy.docx'
        file.close()
        return response
    else:
        title = 'Umowy'
        initial = {}
        if 'selected_specialization' in request.session:
            initial['specialization'] = request.session['selected_specialization'].id
        specialization_choices = tuple((i.id, i.full_name)
                                       for i in all_specs(teacher, dean))
        start_choices=()
        end_choices=()
        tmp=None
        tmp1=None
        msg=None
        
        for training_date in Training_Date.objects.all():
            if len(training_date.training_set.filter(is_archival=False, locked=True, dont_print_contract=False))==0:
                continue
            if tmp is None:
                tmp=training_date.start_date
                tmp1=training_date.start_date
                initial['startdate']=training_date.id

            if training_date.start_date.year==datetime.today().year and training_date.start_date<tmp:
                initial['startdate']=training_date.id
                tmp=training_date.start_date

            if training_date.end_date>tmp1:
                initial['enddate']=training_date.id
                tmp1=training_date.end_date
            
            start_choices += tuple([(training_date.id,training_date.start_date)])
            end_choices += tuple([(training_date.id,training_date.end_date)])
        
        if len(end_choices)==0:
            msg='Brak praktyk wymagających umowy'
        
        form = ReportForm(initial=initial,
                                      specchoices=specialization_choices, startchoices=start_choices, endchoices=end_choices)
        return render('reports.html', request, {'title':title, 'form': form, 'msg': msg})

def generate_in_blanco_contract(request):
    createDOCX(settings.DATA_CATALOG + 'in_blanco.docx')
    file=open(settings.DATA_CATALOG + 'in_blanco.docx', 'r')
    response = HttpResponse(file.read(), mimetype='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
    response['Content-Disposition'] = 'attachment; filename=in_blanco.docx'
    file.close()
    return response
